<template>
  <CommonDialog v-model="visible" title="重命名" :width="400" @submit="submit" @cancel="cancel">
    <Form ref="formEl" :model="formData" :rules="rules" :label-width="80">
      <FormItem label="文件名称" prop="title">
        <Input v-model="formData.title"/>
      </FormItem>
    </Form>
  </CommonDialog>
</template>

<script setup>
import { onMounted, ref, inject } from 'vue'
import { Message } from 'view-ui-plus'

import { myKnowledge } from '@/api/modules/knowledgeBase'

import UploadFile from '@/pages/knowledgeBase/MyKnowledge/CreateKnowledge/components/UploadFile.vue'

const emit = defineEmits(['cancel', 'submit'])

// 是否打开弹窗
const visible = ref(true)

// 加载状态
const loading = ref(false)

const dataId = ref(undefined)
// 表单元素ref
const formEl = ref(null)
// 表单数据
const formData = ref({
  title: ''
})

// 表单校验条件
const rules = ref({
  title: [{ required: true, message: '请填写名称', trigger: 'blur' }]
})

const getTypeId = inject('getTypeId')

let tableId = null
/**
 * 提交表单
 */
const submit = async () => {
  let valid = await formEl.value.validate()
  if (!valid) return

  loading.value = true

  try {
    await myKnowledge.fileedit({
      data: {
        title: formData.value.title,
        id: tableId
      }
    })
    
    emit('success')
  } catch (error) {
    console.error(error)
  }

  loading.value = false
}

/**
 * 取消表单
 */
const cancel = () => {
  visible.value = false
  emit('cancel')
}

/**
 * 初始化对话框
 */
const initData = (data) => {
  // 显示对话框
  visible.value = true

  tableId = data?.id
  formData.value.title = data.title
}

defineExpose({
  initData
})
</script>

<style scoped lang="scss">
.flex-form {
  display: flex;
}
</style>
